package pers.cz.exception;

import java.lang.reflect.Field;

/**
 * @program: PostGirl-panent
 * @description: 服务于异常类
 * @author: Cheng Zhi
 * @create: 2022-10-04 22:21
 **/
public class ExceptionUtil {

    /**
     * 根据BusinessException对象获得ErrorCode中对应的中文描述
     * @param e
     * @return
     */
    public static String getBaseExceptionText(BaseException e, String... paramters) {
        Class<ErrorCode> clazz = ErrorCode.class;
        ErrorCode errorCode = new ErrorCode();
        Field[] fields = clazz.getDeclaredFields(); // 获取所有ErrorCode类中申明的字段

        for(int i=0; i<fields.length; ++i) {
            try {
                String temp = fields[i].get(errorCode).toString();
                if(temp.equals(e.getMessageCode())) {
                    ErrorMessage msg = fields[i].getAnnotation(ErrorMessage.class);
                    String exceptionDes = msg.text();
                    if (paramters.length > 0) {
                        // 如果有参数，需要增加到异常描述后面
                        for (String paramter : paramters) {
                            exceptionDes = exceptionDes + ":" + paramter + ",";
                        }
                    }
                    return exceptionDes;
                }
            } catch (IllegalArgumentException ex) {
            } catch (IllegalAccessException ex) {
            }
        }

        return e.getMessageCode();
    }
}
